package javase.javase02.thread;


import java.io.*;
import java.text.DecimalFormat;
import java.util.concurrent.*;

/**
 * @author: Gan
 * @date 2021/4/22 0022 17:07
 * @description: **4.用Callable的方式去实现之前的多线程文件复制**
 * 复制成功后,返回复制成功的文件路径,并利用Callable的方式接收返回值,然后把这几个路径都保存到新的文件中.
 **/
public class Day21Work04 {
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        FileWriter fileWriter = new FileWriter("c.txt");
        FutureTask task1 = new FutureTask(new CopyFile("b.txt", "a.txt"));
        FutureTask task2 = new FutureTask(new CopyFile("b.txt", "a.txt"));
        FutureTask task3 = new FutureTask(new CopyFile("b.txt", "a.txt"));
        Thread t1 = new Thread(task1);
        Thread t2 = new Thread(task2);
        Thread t3 = new Thread(task3);
        t1.setName("线程一");
        t2.setName("线程二");
        t3.setName("线程三");
        t1.start();
        t2.start();
        t3.start();
        String str1 = String.valueOf(task1.get());
        String str2 = String.valueOf(task1.get());
        String str3 = String.valueOf(task1.get());
        fileWriter.write(str1);
        fileWriter.write(str2);
        fileWriter.write(str3);
        fileWriter.close();
    }
}

class CopyFile implements Callable {
    public File oldFile;
    public File newFile;

    public CopyFile(String oldFile, String newFile) {
        this.oldFile = new File(oldFile);
        this.newFile = new File(newFile);
    }

    @Override
    public Object call() throws Exception {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(newFile);
            fis = new FileInputStream(oldFile);
            //声明一个数组，每次读取的数据放在数组里
            byte[] bytes = new byte[1024];
            //返回每次读取的数据长度
            int readCount = 0;
            //原文件长度
            long len = oldFile.length();
            //声明数据格式为百分比形式
            double temp = 0;
            DecimalFormat decimalFormat = new DecimalFormat("##%");
            while ((readCount = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, readCount);
                //每次读取数据文件长度累加
                temp += readCount;
                //每次读取文件长度占总文件的比例
                double d = temp / len;
                int d1 = (int) d;
                if (d1 % 10 == 0) {
                    System.out.println(Thread.currentThread().getName() + "复制了：" + decimalFormat.format(d));
                }
            }
            System.out.println(Thread.currentThread().getName()+ "已经复制完成！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return newFile.getAbsoluteFile();
    }
}
